import request from '../utils/request'

// 用户相关接口
export const userApi = {
  // 登录
  login: (data) => {
    // 打印请求数据
    console.log('登录请求数据:', {
      phone: data.username,
      pwd: data.password
    })
    
    return request({
      url: '/users/login',
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        phone: data.username,
        pwd: data.password
      }
    })
  },
  
  // 获取用户信息
  getUserInfo: (t_id) => {
    return request({
      url: `/users/${t_id}`,  // 根据用户ID获取用户信息
      method: 'GET'
    })
  },
  
  // 获取用户积分
  getUserScore: (t_id) => {
    return request({
      url: `/customerInfo/score?t_id=${t_id}`,  // 将参数放在URL中
      method: 'GET'
    })
  },

  // 更新用户积分
  updateUserScore: (t_id, point) => {
    return request({
      url: `/customerInfo/updateScore?t_id=${t_id}&point=${point}`,
      method: 'POST'
    })
  },
  
  // 修改密码
  changePassword: (data) => {
    return request({
      url: `/users/${data.uId}`,
      method: 'PUT',
      data
    })
  },

  // 修改个人信息
  updateUserInfo: (data) => {
    return request({
      url: `/users/${data.uId}`,
      method: 'PUT',
      data
    })
  },
  // 验证原密码
  verifyOldPassword: (data) => {
    return request({
      url: `/users/verify/${data.uId}`,
      method: 'GET',
      data:data
    })
  },
  // 更新用户余额（充值）
  updateUserBalance: (t_id, point) => {
    const data = `t_id=${encodeURIComponent(t_id)}&point=${encodeURIComponent(point)}`
    const token = uni.getStorageSync('token')
    const header = {
      'Content-Type': 'application/x-www-form-urlencoded',
      'X-Requested-With': 'XMLHttpRequest'
    }
    if (token) {
      header['auth'] = `Bearer ${token}`
    }
    return request({
      url: '/customerInfo/updSurplus',
      method: 'POST',
      data,
      header
    })
  }
}

// 菜品相关接口
export const dishApi = {
  // 获取菜品列表
  getDishList: () => {
    return request({
      url: '/dishesDTO/list',
      method: 'GET'
    })
  },
  
  // 获取菜品分类
  getDishTypes: () => {
    return request({
      url: '/dishes/types',
      method: 'GET'
    })
  },
  
  // 检查菜品可用性（根据ID列表批量检查菜品状态）
  checkDishAvailability: (requestBody) => {
    return request({
      url: '/order/submit',
      method: 'POST',
      data: requestBody
    })
  },

  
} 

// 餐桌相关接口
export const boardApi = {
  getBoardById: (boardId) => {
    return request({
      url: `/board/${boardId}`,
      method: 'GET'
    })
  },
  updBoard: (data) => {
    return request({
      url: '/board/upd',
      method: 'POST',
      data
    })
  }
}

// 订单相关接口
export const orderApi = {
  // 获取订单列表
  getOrderList: (t_id) => {
    return request({
      url: `/ordersDTO/orderDto?t_id=${t_id}`,
      method: 'GET'
    })
  },
  // 创建订单
  createOrder: (data) => {
    return request({
      url: '/orders',
      method: 'POST',
      data
    })
  },
  //创建订单+订单项
  insertOrder: (data) => {
    return request({
      url: '/orders/insert',
      method: 'POST',
      data
    })
  },
  // 获取订单详情
  getOrderDetail: (orderId) => {
    return request({
    url: `/ordersDTO/${orderId}`,
      method: 'GET'
    })  
  },  
  updOrder: (orderId) => {
    return request({
    url: `/orders/${orderId}`,
      method: 'GET'
    })  
  },  
  // 获取指定日期的订单信息
  getOrdersByDate: (date) => {
    return request({
      url: date ? `/orders/date?date=${date}` : '/orders/date',
      method: 'GET'
    })
  },
  //获取可退款订单
  listRefundOrders: (uId) => {
    return request({
      url: `/orders/refund-order/${uId}`,
      method: 'GET'
    })
  },
  // 确认库存
  confirmInventory: (orderId) => {
    return request({
      url: '/order/confirm',
      method: 'POST',
      data: {
        orderId: orderId
      }
    })
  }
} 

// 优惠券相关接口
export const couponApi = {
  //根据ID获取优惠卷列表信息
  getCouponListByUserId: (uId) => {
    return request({
      url: `/coupons/coupon-user/${uId}`,
      method: 'GET'
    })
  },
  //获取优惠卷列表信息
  getCouponList: () => {
    return request({
      url: '/coupons/couponInfo',
      method: 'GET'
    })
  },
  // 兑换优惠券
  exchangeCoupon: (customer_id, coupon_id, deadline_time) => {
    return request({
      url: `/coupons/add?customer_id=${customer_id}&coupon_id=${coupon_id}&deadline_time=${deadline_time}`,
      method: 'POST'
    })
  },
  // 使用优惠券
  useCoupon: (customerId, couponId) => {
    const token = uni.getStorageSync('token')
    const header = {
      'X-Requested-With': 'XMLHttpRequest'
    }
    if (token) {
      header['auth'] = `Bearer ${token}`
    }
    return request({
      url: `/cus-cou/useCoupon?customerId=${encodeURIComponent(customerId)}&couponId=${encodeURIComponent(couponId)}`,
      method: 'DELETE',
      header
    })
  }
} 

// 我的相关接口
export const mineApi = {
  // 获取我的信息
  getMyInfo: (t_id) => {
    return request({
      url: `/mineDTO/info?t_id=${t_id}`,
      method: 'GET'
    })
  }
}

// 地址相关接口
export const addressApi = {
  // 获取地址列表 - 根据账户编号
  getAddressList: (uId) => {
    return request({
      url: `/address/list/${uId}`,
      method: 'GET'
    })
  },
  // 获取地址详情 - 根据地址编号
  getAddressDetail: (addressId) => {
    return request({
      url: `/address/${addressId}`,
      method: 'GET'
    })
  },
  // 保存地址
  saveAddress: (data) => {
    return request({
      url: '/address',
      method: data.addressId ? 'PUT' : 'POST',
      data
    })
  },
  // 删除地址
  deleteAddress: (addressId) => {
    return request({
      url: `/address/${addressId}`,
      method: 'POST'
    })
  }
}

export const customerApi = {
  //获取个人信息
  getCustomerInfo: (uId) => {
    return request({
      url: `/customerDTO/customer-info/${uId}`,
      method: 'GET'
    })
  },

  /**
   * 通过uId获取customerId
   * @param {number} uId - 账户ID
   * @returns {Promise} - 返回包含customerId的请求结果
   */
  useCusIdFindUId: (uId) => {
    return request({
      url: `/customerInfo/useCusIdFindUId?uId=${uId}`,
      method: 'GET'
    });
  }
}

// 支付记录相关接口
export const payHistoryApi = {
  /**
   * 添加支付记录
   * @param {string} token - 用户token
   * @param {Object} payHistory - 支付记录数据
   * @returns {Promise} - 返回请求结果
   */
  addPayHistory(token, payHistory) {
    // 打印完整的请求信息
    console.log('原始支付记录数据:', payHistory)
    
    // 确保数据格式正确，字段名与后端实体类完全匹配
    const requestData = {
      order_id: payHistory.order_id,  // 使用下划线命名
      u_id: payHistory.u_id,
      pay_amount: payHistory.pay_amount,
      pay_way: payHistory.pay_way,
      pay_time: payHistory.pay_time
    }
    
    console.log('处理后的请求数据:', requestData)
    
    return request({
      url: '/payHistory/addOne',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'auth': token
      },
      data: requestData
    })
  },

  /**
   * 获取用户的支付记录
   * @param {string} token - 用户token
   * @param {number} u_id - 用户ID
   * @returns {Promise} - 返回请求结果
   */
  getPayHistory(token, u_id) {
    return request({
      url: '/payHistory/getAllForId',
      method: 'GET',
      header: {
        'auth': token
      },
      params: {
        u_id: u_id
      }
    })
  },

  /**
   * 批量添加订单菜品项
   * @param {string} token - 用户token
   * @param {Array} items - 订单项数组
   * @returns {Promise} - 返回请求结果
   */
  addOrderItems(token, items) {
    return request({
      url: '/payHistory/addOrderItems',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'auth': token
      },
      data: items
    })
  }
}

export const refundApi = {
  submitRefund: (refundRequest) => {
    return request({
      url: '/refundDTO/save-refund',
      method: 'POST',
      data: refundRequest
    })
  },
  listRefundRequestByUserId: (uId) => {
    return request({
      url: `/refund-request/${uId}`,
      method: 'GET'
    })
  },
  getRefundDetail: (rrId) => {
    return request({
      url: `/refund-request/request/${rrId}`,
      method: 'GET'
    })
  },
  listRefundImages: (rrId) => {
    return request({
      url: `/refund-image/list/${rrId}`,
      method: 'GET'
    })
  },
  cancelRefund: (rrId) => {
    return request({
      url: `/refund-request/cancel/${rrId}`,
      method: 'POST'
    })
  }
}